<template>
  <div class="container">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6" :offset="0">
          <el-input
            v-model="listQuery.title"
            placeholder="请输入标题关键词"
            size="small"
          ></el-input>
        </el-col>
        <el-col :span="4" :offset="0">
          <el-cascader
            :options="sortList"
            :value="sortObject"
            size="small"
            clearable=""
            :show-all-levels="false"
            :props="{
              expandTrigger: 'hover'
            }"
            @change="sort1Change"
          >
          </el-cascader>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-button type="primary" size="small" @click="getList()"
            >搜索</el-button
          >
          <el-button type="primary" size="small" @click="resList()"
            >重置</el-button
          >
        </el-col>
      </el-row>
      <el-divider direction="horizontal" content-position="left"></el-divider>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-button type="primary" size="small" @click="showAdd()"
            >新增</el-button
          >
        </el-col>
      </el-row>

      <el-divider direction="horizontal" content-position="left"></el-divider>

      <el-table v-loading="loading" :data="List" border stripe>
        <el-table-column
          align="center"
          label="标题"
          prop="title"
        ></el-table-column>
        <el-table-column
          align="center"
          label="性别"
          prop="sex"
          width="50px"
        ></el-table-column>
        <el-table-column align="center" label="类型" width="150px" prop="type" >
          <template slot-scope="{ row }">
            {{ row.sort_text || row.sex + "频" }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="数量"
          prop="total"
          width="60px"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" plain @click="showUpdate(row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" plain @click="showDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </el-card>

    <el-dialog
      title="编辑"
      :visible.sync="update_vis"
      width="80%"
      @close="
        row = { list: [] };
        activeName = -1;
        active = '0';
        sortList[1].disabled = false;
        sortList[0].disabled = false;
      "
    >
      <el-tabs v-model="active" type="border-card">
        <el-tab-pane label="基础信息" name="0">
          <el-form
            :model="row"
            ref="form"
            label-width="80px"
            :inline="false"
            size="normal"
          >
            <el-form-item label="标题">
              <el-input
                v-model="row.title"
                placeholder="请输入标题"
                size="small"
              ></el-input>
            </el-form-item>

            <el-form-item label="性别">
              <el-switch
                v-model="row.sex"
                active-value="女"
                inactive-value="男"
                active-text="女"
                inactive-text="男"
              >
              </el-switch>
            </el-form-item>

            <el-form-item label="类型">
              <el-cascader
                :options="sortList"
                :value="row.sortObject"
                size="small"
                clearable=""
                :show-all-levels="false"
                :props="{
                  expandTrigger: 'hover'
                }"
                @change="sortChange"
              >
              </el-cascader>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="小说列表" name="1">
          自动获取剪贴板：
          <el-switch
            v-model="canGET"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :inactive-value="false"
            :active-value="true"
            active-text="是"
            inactive-text="否"
          ></el-switch>

          <div v-for="(item, index) in row.list" :key="index" class="box">
            <div class="action">
              <i @click="addItem()" class="el-icon-circle-plus-outline add"></i>
              <i
                @click="delItem(index)"
                class="el-icon-remove-outline delete"
              ></i>
            </div>
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item :name="index">
                <el-input
                  v-model="item.des"
                  type="textarea"
                  placeholder="请输入简介"
                  size="small"
                  :autosize="{ minRows: 4 }"
                  @focus="getCliboard(item)"
                ></el-input>
                <div slot="title" style="width:100%;">
                  <el-input
                    v-model="item.title"
                    placeholder="请输入标题"
                    size="small"
                  ></el-input>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer">
        <el-button size="small" @click="update_vis = false">取消</el-button>
        <el-button size="small" type="primary" @click="update()"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="新增书单"
      :visible.sync="add_vis"
      width="80%"
      @close="
        row = { list: [] };
        activeName = -1;
        active = '0';
        canGET = false;
        most = null;
        sortList[1].disabled = false;
        sortList[0].disabled = false;
      "
    >
      <el-tabs v-model="active" type="border-card">
        <el-tab-pane label="基础信息" name="0">
          <el-form
            :model="row"
            ref="form"
            label-width="80px"
            :inline="false"
            size="normal"
          >
            <el-form-item label="标题">
              <el-input
                v-model="row.title"
                placeholder="请输入标题"
                size="small"
              ></el-input>
            </el-form-item>

            <el-form-item label="性别">
              <el-switch
                v-model="row.sex"
                active-value="女"
                inactive-value="男"
                active-text="女"
                inactive-text="男"
              >
              </el-switch>
            </el-form-item>

            <el-form-item label="类型">
              <el-cascader
                :options="sortList"
                :value="row.sortObject"
                size="small"
                clearable=""
                :show-all-levels="false"
                :props="{
                  expandTrigger: 'hover'
                }"
                @change="sortChange"
              >
              </el-cascader>
            </el-form-item>
          </el-form>
          <el-input
            v-model="most"
            placeholder=""
            size="normal"
            type="textarea"
            :autosize="{ minRows: 6 }"
          ></el-input>
          <el-divider
            direction="horizontal"
            content-position="left"
          ></el-divider>

          <el-button type="primary" size="small" @click="slove()"
            >批量导入</el-button
          >
        </el-tab-pane>
        <el-tab-pane label="小说列表" name="1">
          自动获取剪贴板：
          <el-switch
            v-model="canGET"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :inactive-value="false"
            :active-value="true"
            active-text="是"
            inactive-text="否"
          ></el-switch>
          <div v-for="(item, index) in row.list" :key="index" class="box">
            <div class="action">
              <i @click="addItem()" class="el-icon-circle-plus-outline add"></i>
              <i
                @click="delItem(index)"
                class="el-icon-remove-outline delete"
              ></i>
            </div>
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item :name="index">
                <el-input
                  v-model="item.des"
                  type="textarea"
                  placeholder="请输入简介"
                  size="small"
                  @focus="getCliboard(item)"
                  :autosize="{ minRows: 4 }"
                ></el-input>
                <div slot="title" style="width:100%;" class="title">
                  <el-input
                    v-model="item.title"
                    placeholder="请输入标题"
                    size="small"
                  ></el-input>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer">
        <el-button size="small" @click="add_vis = false">取消</el-button>
        <el-button size="small" type="primary" @click="add()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import {
  getBookList,
  updateBookList,
  addBookList,
  delBookList,
  getBookListById,
  getBookListSort
} from "@/api/bookList";
export default {
  components: { Pagination },
  watch: {
    "row.sex"(n, o) {
      console.log(n);
      if (n == "男") {
        this.sortList[1].disabled = true;
        this.sortList[0].disabled = false;
      } else if (n == "女") {
        this.sortList[0].disabled = true;
        this.sortList[1].disabled = false;
      } else {
        this.sortList[0].disabled = false;
        this.sortList[1].disabled = false;
      }
    }
  },
  data() {
    return {
      active: "0",
      activeName: -1,
      sortList: [
        { label: "男频", value: "男频", children: [], disabled: false },
        { label: "女频", value: "女频", children: [], disabled: false }
      ],
      List: [],
      loading: false,
      total: 0,
      row: { list: [] },
      update_vis: false,
      add_vis: false,
      most: null,
      canGET: false,
      listQuery: {
        page: 1,
        limit: 10
      }
    };
  },
  created() {
    this.getList();
    getBookListSort().then(res => {
      for (const s of res) {
        if (s.sex == "男") {
          this.sortList[0].children.push({ label: s.name, value: s.id });
        } else {
          this.sortList[1].children.push({ label: s.name, value: s.id });
        }
      }
    });
  },
  methods: {
    sort1Change(e) {
      if (!e) return;
      this.listQuery.sort = e[1];
      this.listQuery.sex = e[0].replace("频", "");
    },
    sortChange(e) {
      if (!e) return;
      this.row.sort = e[1];
    },
    getCliboard(i) {
      if (!this.canGET) return;
      navigator.clipboard.readText().then(v => {
        i.des = v;
      });
    },
    slove() {
      this.row.list = [];
      let list = this.most.split("\n");
      for (let s of list) {
        if (!s) continue;
        s = s.replace(/ /g, "");
        if (s.indexOf("作者") == -1) {
          s = "《" + s + "》".replace(/ /g, "");
        } else {
          if (s.indexOf("《") == -1) {
            let r = /(.*?)作者/g;
            let name = r.exec(s)[1].replace(/ /g, "");
            s = s
              .replace(new RegExp(`(${name})`, "gs"), "《$1》")
              .replace(/ /g, "");
          }
        }
        this.row.list.push({ title: s, des: "" });
      }
      this.active = "1";
    },
    resList() {
      this.listQuery = {
        page: 1,
        limit: 10
      };
      this.sortObject = {};
      this.getList();
    },
    addItem() {
      this.row.list.push({ title: "", des: "" });
    },
    delItem(index) {
      if (this.row.list.length == 1) {
        this.$notify({
          title: "提示",
          message: "至少保留一个",
          type: "warning"
        });
        return;
      }
      this.row.list.splice(index, 1);
    },
    add() {
      let row = JSON.parse(JSON.stringify(this.row));
      row.list = JSON.stringify(row.list);
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      addBookList(row)
        .then(res => {
          this.$notify({
            title: "成功",
            message: "新增书单成功",
            type: "success"
          });
          this.add_vis = false;
          this.getList();
        })
        .finally(_ => {
          loading.close();
        });
    },
    showAdd() {
      this.row = { list: [{ title: "", des: "" }] };
      this.add_vis = true;
    },
    update() {
      let row = JSON.parse(JSON.stringify(this.row));
      row.list = JSON.stringify(row.list);
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      updateBookList(row)
        .then(res => {
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success"
          });
          this.update_vis = false;
          this.getList();
        })
        .finally(_ => {
          loading.close();
        });
    },
    showUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      getBookListById(row.id).then(res => {
        this.row = res;
        this.row.sortObject = [res.sex + "频", row.sort];
        this.update_vis = true;
        loading.close();
      });
    },
    showDelete(row) {
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        delBookList(row.id)
          .then(res => {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success"
            });
            this.getList();
          })
          .finally(_ => {
            loading.close();
          });
      });
    },
    getList() {
      this.loading = true;
      getBookList(this.listQuery).then(res => {
        this.List = res.results;
        this.total = res.count;
        this.loading = false;
      });
    }
  }
};
</script>

<style scoped>
.box {
  display: flex;
}
.box .el-collapse {
  flex: 1;
}
.container >>> .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  min-height: calc(100% - 30px);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}
.container >>> .el-dialog__body {
  flex: 1;
  overflow: auto;
}
.action {
  height: 48px;
  display: flex;
  align-items: center;
}
.action .add {
  font-size: 20px;
  padding: 5px;
  color: #409eff;
  cursor: pointer;
}
.action .delete {
  font-size: 20px;
  padding: 5px;
  color: #f56c6c;
  cursor: pointer;
}
</style>
